package com.ics.atable.chat.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ics.atable.chat.common.BaseResponse;
import com.ics.atable.chat.model.dto.GetChatHistoryByPageDTO;
import com.ics.atable.chat.model.entity.ChatSession;
import com.ics.atable.chat.model.vo.history.ChatHistoryVO;
import com.ics.atable.chat.service.ChatMessageService;
import com.ics.atable.chat.service.ChatSessionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotBlank;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.ics.atable.chat.common.ResultUtils.success;

/**
 * chat 接口
 *
 * 包含：
 * - 会话相关的 CRUD 及查询端点
 * - 历史消息查询端点
 *
 * 说明：
 * - 统一响应为 {@link com.ics.atable.chat.common.BaseResponse}
 */
@Tag(name = "对话管理")
@RestController
@RequestMapping("/session")
public class ChatController {

    @Resource
    private ChatSessionService chatSessionService;

    @Resource
    private ChatMessageService chatMessageService;


    /**
     * 查询聊天历史消息。
     * @param getChatHistoryByPageDTO 查询参数
     * @return 分页历史消息
     */
    @Operation(summary = "查询聊天历史消息")
    @PostMapping("/message/history")
    public BaseResponse<Page<ChatHistoryVO>> listChatHistory(@RequestBody GetChatHistoryByPageDTO getChatHistoryByPageDTO) {
        Page<ChatHistoryVO> result = chatMessageService.listChatHistory(getChatHistoryByPageDTO.getSessionId(), getChatHistoryByPageDTO.getPageSize(), getChatHistoryByPageDTO.getLastCreateTime());
        return success(result);
    }

    // ===== ChatSession CRUD =====

    /** 创建会话 */
    @Operation(summary = "创建会话")
    @PostMapping("/create")
    public BaseResponse<String> createSession(@RequestBody ChatSession request) {
        String id = chatSessionService.createSession(request);
        return success(id);
    }

    /** 更新会话（只更新非空字段） */
    @Operation(summary = "更新会话")
    @PutMapping("/sessions/{id}")
    public BaseResponse<Boolean> updateSession(@PathVariable("id") String id,
                                               @RequestBody ChatSession request) {
        request.setId(id);
        boolean ok = chatSessionService.updateSession(request);
        return success(ok);
    }

    /** 归档会话（状态置为 archived） */
    @Operation(summary = "归档会话")
    @PostMapping("/sessions/{id}/archive")
    public BaseResponse<Boolean> archiveSession(@PathVariable("id") @NotBlank String id) {
        boolean ok = chatSessionService.archiveSession(id);
        return success(ok);
    }

    /** 逻辑删除会话（状态置为 deleted） */
    @Operation(summary = "删除会话（逻辑删除）")
    @DeleteMapping("/sessions/{id}")
    public BaseResponse<Boolean> deleteSession(@PathVariable("id") @NotBlank String id) {
        boolean ok = chatSessionService.deleteSession(id);
        return success(ok);
    }

    /** 置顶/取消置顶（isPinned=1/0） */
    @Operation(summary = "置顶/取消置顶")
    @PostMapping("/sessions/{id}/pin")
    public BaseResponse<Boolean> pinSession(@PathVariable("id") @NotBlank String id,
                                            @RequestParam("pinned") boolean pinned) {
        boolean ok = chatSessionService.pinSession(id, pinned);
        return success(ok);
    }

    /** 查询用户会话列表（过滤 deleted，置顶优先，更新时间倒序） */
    @Operation(summary = "查询用户会话列表")
    @GetMapping("/sessions")
    public BaseResponse<List<ChatSession>> listSessions(@RequestParam("userId") Long userId) {
        List<ChatSession> list = chatSessionService.listSessionsByUser(userId);
        return success(list);
    }

    /** 分页查询用户会话（过滤 deleted，置顶优先，更新时间倒序） */
    @Operation(summary = "分页查询用户会话")
    @GetMapping("/sessions/page")
    public BaseResponse<Page<ChatSession>> pageSessions(@RequestParam("userId") Long userId,
                                                        @RequestParam(defaultValue = "1") long page,
                                                        @RequestParam(defaultValue = "10") long size) {
        Page<ChatSession> result = chatSessionService.pageSessionsByUser(userId, page, size);
        return success(result);
    }
}
